<template>
  <div class="report-dashboard-container">
    <div class="page-header">
      <h2>统计概览</h2>
      <div class="header-actions">
        <el-dropdown split-button type="primary" @click="exportAsPDF" @command="handleExport">
          导出报表
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item command="pdf">导出为PDF</el-dropdown-item>
              <el-dropdown-item command="excel">导出为Excel</el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
        <el-button type="primary" @click="refreshData" :loading="loading" icon="Refresh" style="margin-left: 10px;">刷新数据</el-button>
      </div>
    </div>

    <div class="dashboard-content" v-loading="loading">
      <!-- 顶部卡片 -->
      <div class="dashboard-cards">
        <el-row :gutter="20">
          <el-col :xs="24" :sm="12" :md="6">
            <el-card shadow="hover" class="data-card">
              <div class="card-content">
                <h3>总活动数</h3>
                <div class="card-value">{{ overview?.totalEvents || 0 }}</div>
                <div class="card-footer">
                  <span class="trend-text">本月新增: {{ overview?.newEventsThisMonth || 0 }}</span>
                </div>
              </div>
            </el-card>
          </el-col>
          <el-col :xs="24" :sm="12" :md="6">
            <el-card shadow="hover" class="data-card">
              <div class="card-content">
                <h3>总用户数</h3>
                <div class="card-value">{{ overview?.totalUsers || 0 }}</div>
                <div class="card-footer">
                  <span class="trend-text">本月新增: {{ overview?.newUsersThisMonth || 0 }}</span>
                </div>
              </div>
            </el-card>
          </el-col>
          <el-col :xs="24" :sm="12" :md="6">
            <el-card shadow="hover" class="data-card">
              <div class="card-content">
                <h3>总销售额</h3>
                <div class="card-value">¥{{ overview?.totalSales?.toFixed(2) || '0.00' }}</div>
                <div class="card-footer">
                  <span class="trend-text">票种售出比例: {{ getSalesRatio() }}</span>
                </div>
              </div>
            </el-card>
          </el-col>
          <el-col :xs="24" :sm="12" :md="6">
            <el-card shadow="hover" class="data-card">
              <div class="card-content">
                <h3>今日活跃</h3>
                <div class="card-value">{{ overview?.activeToday || 0 }}</div>
                <div class="card-footer">
                  <span class="trend-text">问卷提交数: {{ overview?.totalQuestionnaireSubmits || 0 }}</span>
                </div>
              </div>
            </el-card>
          </el-col>
        </el-row>
      </div>

      <!-- 图表区域 -->
      <div class="dashboard-charts">
        <el-row :gutter="20">
          <el-col :xs="24" :lg="12">
            <el-card shadow="hover" class="chart-card">
              <template #header>
                <div class="card-header">
                  <span>活动类型分布</span>
                </div>
              </template>
              <div class="chart-container" ref="categoryChartRef"></div>
            </el-card>
          </el-col>
          <el-col :xs="24" :lg="12">
            <el-card shadow="hover" class="chart-card">
              <template #header>
                <div class="card-header">
                  <span>票种销售情况</span>
                </div>
              </template>
              <div class="chart-container" ref="ticketChartRef"></div>
            </el-card>
          </el-col>
        </el-row>
      </div>

      <!-- 活跃用户预览 -->
      <div class="active-users-preview">
        <el-card shadow="hover">
          <template #header>
            <div class="card-header">
              <span>活跃用户排行 (Top 5)</span>
              <el-button type="text" @click="navigateToUserRanking">查看更多</el-button>
            </div>
          </template>
          <el-table :data="activeUsers" stripe style="width: 100%">
            <el-table-column type="index" label="排名" width="80" />
            <el-table-column prop="username" label="用户名" min-width="120" />
            <el-table-column prop="activityScore" label="活跃度" min-width="100" />
            <el-table-column prop="lastLoginTime" label="最后登录" min-width="160" />
            <el-table-column prop="eventCount" label="参与活动数" min-width="120" />
          </el-table>
        </el-card>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, computed, onBeforeUnmount } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import * as echarts from 'echarts'
import { getReportOverview, getActiveUsers } from '@/api/report'
import * as XLSX from 'xlsx'
import jsPDF from 'jspdf'
import 'jspdf-autotable'
import html2canvas from 'html2canvas'

const router = useRouter()

// 数据状态
const loading = ref(false)
const exporting = ref(false)
const overview = ref(null)
const activeUsers = ref([])

// 图表引用
const categoryChartRef = ref(null)
const ticketChartRef = ref(null)
let categoryChart = null
let ticketChart = null

// 获取售出比例
const getSalesRatio = () => {
  if (!overview.value) return '0%'
  const total = overview.value.totalTickets || 0
  const sold = overview.value.soldTickets || 0
  if (total === 0) return '0%'
  return `${Math.round((sold / total) * 100)}%`
}

// 初始化
onMounted(() => {
  fetchDashboardData()
  window.addEventListener('resize', handleResize)
})

// 销毁前清理事件监听
const beforeUnmount = () => {
  window.removeEventListener('resize', handleResize)
  if (categoryChart) categoryChart.dispose()
  if (ticketChart) ticketChart.dispose()
}

// 处理窗口大小变化
const handleResize = () => {
  if (categoryChart) categoryChart.resize()
  if (ticketChart) ticketChart.resize()
}

// 获取仪表盘数据
const fetchDashboardData = async () => {
  loading.value = true
  try {
    const res = await getReportOverview()
    if (res.code === 200 && res.data) {
      overview.value = res.data
      await fetchActiveUserData()
      initCharts()
    } else {
      ElMessage.error(res.msg || '获取统计数据失败')
    }
  } catch (error) {
    console.error('获取统计数据出错:', error)
    ElMessage.error('获取统计数据失败')
  } finally {
    loading.value = false
  }
}

// 获取活跃用户数据
const fetchActiveUserData = async () => {
  try {
    const res = await getActiveUsers({ top: 5 })
    if (res.code === 200 && res.data) {
      activeUsers.value = res.data
    } else {
      console.error('获取用户排行失败:', res.msg)
    }
  } catch (error) {
    console.error('获取用户排行出错:', error)
  }
}

// 初始化图表
const initCharts = () => {
  // 确保DOM元素已挂载
  if (!categoryChartRef.value || !ticketChartRef.value) return
  
  // 初始化活动类型饼图
  categoryChart = echarts.init(categoryChartRef.value)
  const categoryData = overview.value.topCategories.map((category, index) => ({
    name: category,
    value: 100 - index * 15 // 模拟数据
  }))
  
  categoryChart.setOption({
    tooltip: {
      trigger: 'item',
      formatter: '{a} <br/>{b}: {c} ({d}%)'
    },
    legend: {
      orient: 'vertical',
      right: 10,
      top: 'center',
      data: categoryData.map(item => item.name)
    },
    series: [
      {
        name: '活动类型',
        type: 'pie',
        radius: ['50%', '70%'],
        avoidLabelOverlap: false,
        itemStyle: {
          borderRadius: 10,
          borderColor: '#fff',
          borderWidth: 2
        },
        label: {
          show: false,
          position: 'center'
        },
        emphasis: {
          label: {
            show: true,
            fontSize: '18',
            fontWeight: 'bold'
          }
        },
        labelLine: {
          show: false
        },
        data: categoryData
      }
    ]
  })
  
  // 初始化票种销售情况图
  ticketChart = echarts.init(ticketChartRef.value)
  
  ticketChart.setOption({
    tooltip: {
      trigger: 'item'
    },
    legend: {
      bottom: '5%',
      left: 'center'
    },
    series: [
      {
        name: '票种销售',
        type: 'pie',
        radius: '55%',
        center: ['50%', '40%'],
        data: [
          { value: overview.value.soldTickets, name: '已售出' },
          { value: overview.value.totalTickets - overview.value.soldTickets, name: '未售出' }
        ],
        emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: 'rgba(0, 0, 0, 0.5)'
          }
        }
      }
    ]
  })
}

// 刷新数据
const refreshData = () => {
  fetchDashboardData()
}

// 跳转到用户排行详情页
const navigateToUserRanking = () => {
  router.push('/report/user-ranking')
}

// 导出处理
const handleExport = (command) => {
  if (command === 'pdf') {
    exportAsPDF()
  } else if (command === 'excel') {
    exportAsExcel()
  }
}

// 导出为PDF
const exportAsPDF = () => {
  if (exporting.value) return
  exporting.value = true
  
  ElMessage.info('正在生成PDF，请稍候...')
  
  // 创建一个新的容器，用于PDF导出
  const element = document.createElement('div')
  element.className = 'pdf-export-container'
  element.innerHTML = `
    <div style="font-family: 'SimSun', Arial, sans-serif; color: #333; padding: 20px;">
      <div style="text-align: center; margin-bottom: 20px;">
        <h1 style="font-size: 24px; margin-bottom: 10px;">统计概览报表</h1>
        <p style="color: #666; font-size: 14px; text-align: right;">导出时间: ${new Date().toLocaleString()}</p>
        <hr style="border: 0; border-top: 1px solid #eee; margin: 20px 0;">
      </div>
      
      <table style="width: 100%; border-collapse: collapse; margin-bottom: 30px; border: 1px solid #ddd;">
        <tr style="background-color: #f5f7fa;">
          <th colspan="4" style="padding: 12px; text-align: left; font-size: 16px; border: 1px solid #ddd;">数据摘要</th>
        </tr>
        <tr>
          <td style="width: 25%; padding: 15px; border: 1px solid #ddd;">
            <div style="font-size: 14px; color: #666; margin-bottom: 8px;">总活动数</div>
            <div style="font-size: 20px; font-weight: bold; color: #409EFF;">${overview.value?.totalEvents || 0}</div>
            <div style="font-size: 12px; color: #666; margin-top: 5px;">本月新增: ${overview.value?.newEventsThisMonth || 0}</div>
          </td>
          <td style="width: 25%; padding: 15px; border: 1px solid #ddd;">
            <div style="font-size: 14px; color: #666; margin-bottom: 8px;">总用户数</div>
            <div style="font-size: 20px; font-weight: bold; color: #409EFF;">${overview.value?.totalUsers || 0}</div>
            <div style="font-size: 12px; color: #666; margin-top: 5px;">本月新增: ${overview.value?.newUsersThisMonth || 0}</div>
          </td>
          <td style="width: 25%; padding: 15px; border: 1px solid #ddd;">
            <div style="font-size: 14px; color: #666; margin-bottom: 8px;">总销售额</div>
            <div style="font-size: 20px; font-weight: bold; color: #409EFF;">¥${overview.value?.totalSales?.toFixed(2) || '0.00'}</div>
            <div style="font-size: 12px; color: #666; margin-top: 5px;">票种售出比例: ${getSalesRatio()}</div>
          </td>
          <td style="width: 25%; padding: 15px; border: 1px solid #ddd;">
            <div style="font-size: 14px; color: #666; margin-bottom: 8px;">今日活跃</div>
            <div style="font-size: 20px; font-weight: bold; color: #409EFF;">${overview.value?.activeToday || 0}</div>
            <div style="font-size: 12px; color: #666; margin-top: 5px;">问卷提交数: ${overview.value?.totalQuestionnaireSubmits || 0}</div>
          </td>
        </tr>
      </table>
    </div>
  `
  
  // 将元素临时添加到文档中以供导出
  document.body.appendChild(element)
  element.style.position = 'absolute'
  element.style.left = '-9999px'
  element.style.width = '800px'
  element.style.backgroundColor = 'white'
  
  // 获取预先渲染的图表数据URL
  const categoryChartURL = categoryChart ? categoryChart.getDataURL({ backgroundColor: '#fff', pixelRatio: 3 }) : null
  const ticketChartURL = ticketChart ? ticketChart.getDataURL({ backgroundColor: '#fff', pixelRatio: 3 }) : null
  
  // 添加图表区域
  const chartsDiv = document.createElement('div')
  chartsDiv.style.padding = '0 20px 20px 20px'
  chartsDiv.style.backgroundColor = 'white'
  chartsDiv.style.fontFamily = "'SimSun', Arial, sans-serif"
  
  chartsDiv.innerHTML = `
    <table style="width: 100%; border-collapse: collapse; margin-bottom: 30px; border: 1px solid #ddd;">
      <tr style="background-color: #f5f7fa;">
        <th colspan="2" style="padding: 12px; text-align: left; font-size: 16px; border: 1px solid #ddd;">图表分析</th>
      </tr>
      <tr>
        <td style="width: 50%; padding: 15px; border: 1px solid #ddd; text-align: center; vertical-align: top;">
          <div style="font-size: 14px; font-weight: bold; margin-bottom: 10px;">活动类型分布</div>
          ${categoryChartURL ? 
            `<img src="${categoryChartURL}" style="max-width: 300px; height: auto;">` : 
            `<p style="color: #999; padding: 40px 0;">无图表数据</p>`
          }
        </td>
        <td style="width: 50%; padding: 15px; border: 1px solid #ddd; text-align: center; vertical-align: top;">
          <div style="font-size: 14px; font-weight: bold; margin-bottom: 10px;">票种销售情况</div>
          ${ticketChartURL ? 
            `<img src="${ticketChartURL}" style="max-width: 300px; height: auto;">` : 
            `<p style="color: #999; padding: 40px 0;">无图表数据</p>`
          }
        </td>
      </tr>
    </table>
  `
  
  element.appendChild(chartsDiv)
  
  // 添加活跃用户表格
  const usersDiv = document.createElement('div')
  usersDiv.style.padding = '0 20px 20px 20px'
  usersDiv.style.backgroundColor = 'white'
  usersDiv.style.fontFamily = "'SimSun', Arial, sans-serif"
  
  let userTableHTML = `
    <table style="width: 100%; border-collapse: collapse; margin-bottom: 30px; border: 1px solid #ddd;">
      <tr style="background-color: #f5f7fa;">
        <th colspan="5" style="padding: 12px; text-align: left; font-size: 16px; border: 1px solid #ddd;">活跃用户排行</th>
      </tr>
      <tr style="background-color: #f8f8f8;">
        <th style="padding: 10px; border: 1px solid #ddd; text-align: center;">排名</th>
        <th style="padding: 10px; border: 1px solid #ddd; text-align: left;">用户名</th>
        <th style="padding: 10px; border: 1px solid #ddd; text-align: center;">活跃度</th>
        <th style="padding: 10px; border: 1px solid #ddd; text-align: center;">最后登录</th>
        <th style="padding: 10px; border: 1px solid #ddd; text-align: center;">参与活动数</th>
      </tr>
  `
  
  activeUsers.value.forEach((user, index) => {
    userTableHTML += `
      <tr style="background-color: ${index % 2 === 0 ? '#fff' : '#f9f9f9'}">
        <td style="padding: 8px; border: 1px solid #ddd; text-align: center;">${index + 1}</td>
        <td style="padding: 8px; border: 1px solid #ddd; text-align: left;">${user.username}</td>
        <td style="padding: 8px; border: 1px solid #ddd; text-align: center;">${user.activityScore}</td>
        <td style="padding: 8px; border: 1px solid #ddd; text-align: center;">${user.lastLoginTime || '-'}</td>
        <td style="padding: 8px; border: 1px solid #ddd; text-align: center;">${user.eventCount}</td>
      </tr>
    `
  })
  
  userTableHTML += `</table>`
  usersDiv.innerHTML = userTableHTML
  
  element.appendChild(usersDiv)
  
  // 添加页脚
  const footerDiv = document.createElement('div')
  footerDiv.style.padding = '0 20px 20px 20px'
  footerDiv.style.backgroundColor = 'white'
  footerDiv.style.fontFamily = "'SimSun', Arial, sans-serif"
  
  footerDiv.innerHTML = `
    <hr style="border: 0; border-top: 1px solid #eee; margin: 20px 0;">
    <p style="text-align: center; color: #999; font-size: 12px;">© ${new Date().getFullYear()} 活动管理系统 - 统计报表</p>
  `
  
  element.appendChild(footerDiv)
  
  // 使用html2canvas和jsPDF
  setTimeout(() => {
    html2canvas(element, {
      scale: 2,
      useCORS: true,
      logging: false,
      allowTaint: true,
      backgroundColor: '#FFFFFF'
    }).then(canvas => {
      // 删除临时元素
      document.body.removeChild(element)
      
      const imgData = canvas.toDataURL('image/jpeg', 1.0)
      const pdf = new jsPDF('p', 'mm', 'a4')
      const pdfWidth = pdf.internal.pageSize.getWidth()
      const pdfHeight = pdf.internal.pageSize.getHeight()
      const imgWidth = canvas.width
      const imgHeight = canvas.height
      const ratio = Math.min(pdfWidth / imgWidth, pdfHeight / imgHeight)
      const imgX = (pdfWidth - imgWidth * ratio) / 2
      const imgY = 0
      
      pdf.addImage(imgData, 'JPEG', imgX, imgY, imgWidth * ratio, imgHeight * ratio)
      pdf.save(`统计概览报表_${new Date().toISOString().split('T')[0]}.pdf`)
      
      exporting.value = false
      ElMessage.success('PDF导出成功')
    }).catch(error => {
      console.error('PDF导出失败:', error)
      document.body.removeChild(element)
      exporting.value = false
      ElMessage.error('PDF导出失败')
    })
  }, 1000) // 给足够时间让内容渲染完成
}

// 导出为Excel
const exportAsExcel = () => {
  if (exporting.value) return
  exporting.value = true
  
  ElMessage.info('正在生成Excel文件，请稍候...')
  
  try {
    // 准备数据
    const workbook = XLSX.utils.book_new()
    
    // 添加文档属性
    workbook.Props = {
      Title: "统计概览报表",
      Subject: "活动管理系统数据报表",
      Author: "活动管理系统",
      CreatedDate: new Date()
    }
    
    // 1. 创建概览数据工作表
    const overviewData = [
      ['统计概览报表', ''],
      ['导出时间', new Date().toLocaleString()],
      [''],
      ['基本数据', ''],
      ['指标', '数值', '说明'],
      ['总活动数', overview.value?.totalEvents || 0, '系统中所有活动的总数'],
      ['本月新增活动', overview.value?.newEventsThisMonth || 0, '本月内新创建的活动数量'],
      ['总用户数', overview.value?.totalUsers || 0, '系统注册用户总数'],
      ['本月新增用户', overview.value?.newUsersThisMonth || 0, '本月内新注册的用户数量'],
      ['总销售额', overview.value?.totalSales || 0, '所有票务销售总金额'],
      ['票种总数', overview.value?.totalTickets || 0, '所有活动的票种总数'],
      ['已售出票数', overview.value?.soldTickets || 0, '已售出的票数量'],
      ['票种售出比例', getSalesRatio(), '已售出票数占总票数的百分比'],
      ['今日活跃用户', overview.value?.activeToday || 0, '今日登录或有行为的用户数'],
      ['问卷提交数', overview.value?.totalQuestionnaireSubmits || 0, '用户提交的问卷总数'],
      [''],
      ['活动类型分布', ''],
      ...overview.value?.topCategories.map((category, index) => [
        category, 
        100 - index * 15, // 模拟数据
        '活动类型及其数量'
      ]) || [],
      [''],
      ['销售分析', ''],
      ['票种类型', '数量', '占比'],
      ['已售出', overview.value?.soldTickets || 0, getSalesRatio()],
      ['未售出', (overview.value?.totalTickets || 0) - (overview.value?.soldTickets || 0), (100 - parseInt(getSalesRatio())) + '%']
    ]
    
    const overviewSheet = XLSX.utils.aoa_to_sheet(overviewData)
    
    // 设置列宽
    const colWidths = [
      { wch: 20 }, // A列宽
      { wch: 15 }, // B列宽
      { wch: 40 }  // C列宽
    ]
    overviewSheet['!cols'] = colWidths
    
    // 合并单元格
    overviewSheet['!merges'] = [
      { s: { r: 0, c: 0 }, e: { r: 0, c: 2 } }, // 合并标题行
      { s: { r: 3, c: 0 }, e: { r: 3, c: 2 } }, // 合并"基本数据"行
      { s: { r: 16, c: 0 }, e: { r: 16, c: 2 } }, // 合并"活动类型分布"行
      { s: { r: overview.value?.topCategories.length + 17, c: 0 }, e: { r: overview.value?.topCategories.length + 17, c: 2 } } // 合并"销售分析"行
    ]
    
    XLSX.utils.book_append_sheet(workbook, overviewSheet, '统计概览')
    
    // 2. 创建活跃用户工作表
    const usersHeader = ['排名', '用户名', '活跃度', '最后登录', '参与活动数', '用户ID', '注册时间', '邮箱']
    const usersData = [usersHeader]
    
    activeUsers.value.forEach((user, index) => {
      usersData.push([
        index + 1,
        user.username,
        user.activityScore,
        user.lastLoginTime,
        user.eventCount,
        user.userId || '-',
        user.registerTime || '-',
        user.email || '-'
      ])
    })
    
    const usersSheet = XLSX.utils.aoa_to_sheet(usersData)
    
    // 设置列宽
    usersSheet['!cols'] = [
      { wch: 8 },  // 排名
      { wch: 20 }, // 用户名
      { wch: 10 }, // 活跃度
      { wch: 20 }, // 最后登录
      { wch: 15 }, // 参与活动数
      { wch: 15 }, // 用户ID
      { wch: 20 }, // 注册时间
      { wch: 25 }  // 邮箱
    ]
    
    XLSX.utils.book_append_sheet(workbook, usersSheet, '活跃用户排行')
    
    // 3. 创建系统信息工作表
    const sysInfoData = [
      ['系统信息', ''],
      ['报表生成时间', new Date().toLocaleString()],
      ['报表类型', '统计概览报表'],
      ['导出用户', '管理员'],
      ['系统版本', '1.0.0'],
      ['数据截止时间', new Date().toLocaleString()],
      [''],
      ['备注', '本报表数据仅供参考，详细数据请以系统实际记录为准。'],
    ]
    
    const sysInfoSheet = XLSX.utils.aoa_to_sheet(sysInfoData)
    XLSX.utils.book_append_sheet(workbook, sysInfoSheet, '报表信息')
    
    // 4. 导出数据
    XLSX.writeFile(workbook, `统计概览报表_${new Date().toISOString().split('T')[0]}.xlsx`)
    
    exporting.value = false
    ElMessage.success('Excel导出成功')
  } catch (error) {
    console.error('Excel导出失败:', error)
    exporting.value = false
    ElMessage.error('Excel导出失败')
  }
}
</script>

<style scoped>
.report-dashboard-container {
  animation: fadeIn 0.3s ease-out;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
  background-color: var(--card-background);
  padding: 20px 24px;
  border-radius: var(--radius-medium);
  box-shadow: var(--shadow-base);
}

.page-header h2 {
  margin: 0;
  font-size: 22px;
  font-weight: 600;
  color: var(--text-primary);
  display: flex;
  align-items: center;
}

.page-header h2::before {
  content: '';
  display: inline-block;
  width: 4px;
  height: 20px;
  background: linear-gradient(180deg, var(--primary-color), #4d7aff);
  margin-right: 12px;
  border-radius: 2px;
}

.header-actions {
  display: flex;
  gap: 12px;
  align-items: center;
}

.dashboard-cards {
  margin-bottom: 20px;
}

.data-card {
  height: 100%;
  transition: all 0.3s;
}

.data-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 10px 15px rgba(0, 0, 0, 0.1);
}

.card-content {
  text-align: center;
  padding: 10px;
}

.card-content h3 {
  margin: 0 0 10px 0;
  font-size: 16px;
  color: #666;
}

.card-value {
  font-size: 28px;
  font-weight: bold;
  margin-bottom: 10px;
  color: var(--primary-color);
}

.card-footer {
  font-size: 14px;
  color: #999;
}

.dashboard-charts {
  margin-bottom: 20px;
}

.chart-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.chart-container {
  height: 300px;
  width: 100%;
}

.active-users-preview {
  margin-bottom: 20px;
}

@media (max-width: 768px) {
  .el-col {
    margin-bottom: 20px;
  }
}
</style> 